<template>
  <div class="map-wrapper">
    <!-- 顶部左侧悬浮下拉栏组 -->
    <div class="map-header-left">
      <!-- 切换校区 -->
      <el-dropdown @command="handleCampus">
        <el-button type="primary">
          切换区域
          <el-icon class="ml-1"><ArrowDown /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="center">北苑区域</el-dropdown-item>
            <el-dropdown-item command="west">图书馆区域</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <!-- 元素开关下拉复选框 -->
      <el-dropdown>
        <el-button type="primary">
          元素开关
          <el-icon class="ml-1"><ArrowDown /></el-icon>
        </el-button>
        <template #dropdown>
          <!-- 自定义下拉内容：复选框组 -->
          <div class="dropdown-checkbox">
            <el-checkbox-group v-model="checkedElements">
              <el-checkbox
                  v-for="item in elementOptions"
                  :key="item.value"
                  :label="item.value"
              >
                {{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </template>
      </el-dropdown>
    </div>

    <!-- 顶部右侧悬浮栏组 -->
    <div class="map-header-right">
      <el-button @click="handlePrint" type="primary">打印</el-button>
    </div>

    <!-- 地图容器 -->
    <div class="map-container" ref="mapContainer"></div>
  </div>
</template>

<script setup>
import { onMounted, ref, onUnmounted, watch } from 'vue';
import { ArrowDown } from '@element-plus/icons-vue';
import { listElement, getElement, delElement, addElement, updateElement } from "@/api/water/element.js";
import { markersInit, polygonsInit } from '@/api/water/map.js';
import ElementPic from '@/assets/icons/svg/system_green.svg';
import { listArea } from "@/api/water/area.js";
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router';
// 导入区域告警列表接口
import { listAreaWarn } from "@/api/water/AreaWarn";

const router = useRouter();

let map = null;
let elements = [];
const mapContainer = ref(null);
const areaVisible = ref(false);
const loading = ref(true);
let polygons = [];
// 用于存储多边形与区域数据的映射关系
const polygonToArea = ref(new Map());

// 切换校区逻辑
const handleCampus = (command) => {
  console.log('切换校区：', command);
  if (command === 'center') {
    map.centerAndZoom(new BMapGL.Point(114.168202, 30.524314), 18); // 北苑区域中心坐标
  } else if (command === 'west') {
    map.centerAndZoom(new BMapGL.Point(114.167382, 30.519973), 18); // 图书馆区域中心坐标
  }
};

// 元素开关逻辑
const elementOptions = ref([
  { label: '水表', value: 'element' },
  { label: '区域', value: 'area' },
  { label: '标签', value: 'label' },
]);
const checkedElements = ref(['element', 'area', 'label']);
watch(checkedElements, (newVal) => {
  elementOptions.value.forEach(item => {
    if (item.value === 'element') {
      newVal.includes(item.value)
          ? elements.forEach(marker => { map.addOverlay(marker) })
          : elements.forEach(marker => { map.removeOverlay(marker) });
    } else if (item.value === 'area') {
      newVal.includes(item.value)
          ? polygons.forEach(polygon => { map.addOverlay(polygon) })
          : polygons.forEach(polygon => { map.removeOverlay(polygon) });
    }
  });
});

// 打印逻辑
const handlePrint = () => {
  window.print()
}

// 获取昨天日期（格式：YYYY-MM-DD）
const getYesterdayDate = () => {
  const today = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(today.getDate() - 1);
  return yesterday.toISOString().split('T')[0];
};

// 检查区域昨天是否有告警
const hasYesterdayWarn = async (areaName) => {
  const yesterday = getYesterdayDate();
  try {
    const response = await listAreaWarn({
      areaName: areaName,
      warnTime: yesterday,
      pageSize: 1 // 只需判断是否存在数据
    });
    return response.rows && response.rows.length > 0;
  } catch (error) {
    console.error(`查询区域【${areaName}】昨天告警失败`, error);
    return false;
  }
};

onMounted(async () => {
  // 初始化百度地图
  map = new BMapGL.Map(mapContainer.value, { minZoom: 16, maxZoom: 20 });
  map.centerAndZoom(new BMapGL.Point(114.167382, 30.519973), 18);
  map.enableScrollWheelZoom(true);
  map.enableKeyboard(true);
  map.addControl(new BMapGL.ScaleControl());
  map.addControl(new BMapGL.ZoomControl());

  // 水表数据初始化
  try {
    loading.value = true;
    const elementList = await listElement({ pageSize: 10000 });
    if (elementList.code === 200 && elementList.rows) {
      elements = markersInit(map, elementList.rows, ElementPic);
      elements.forEach(marker => { map.addOverlay(marker); });
    }
  } catch (error) {
    console.error('获取水表数据时发生错误', error);
    ElMessage.error('获取水表数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }

  // 区域数据初始化、告警检查及点击事件绑定
  try {
    loading.value = true;
    const areaList = await listArea({ pageSize: 10000 });
    if (areaList.code === 200 && areaList.rows) {
      polygons = polygonsInit(map, areaList.rows);

      // 遍历区域，处理多边形样式和点击事件
      polygons.forEach((polygon, index) => {
        const currentArea = areaList.rows[index];
        polygonToArea.value.set(polygon, currentArea);

        // 检查该区域昨天是否有告警，有则设置红色样式
        hasYesterdayWarn(currentArea.areaName).then(hasWarn => {
          if (hasWarn) {
            polygon.setOptions({
              fillColor: "#ff0000", // 填充色为红色
              strokeColor: "#ff0000", // 边框色为红色
              fillOpacity: 0.5, // 填充透明度（可选，调整视觉效果）
              strokeOpacity: 0.8 // 边框透明度（可选，调整视觉效果）
            });
          }
        });

        // 绑定区域点击跳转事件
        polygon.addEventListener('click', () => {
          const areaData = polygonToArea.value.get(polygon);
          const areaName = areaData.areaName;
          const yesterday = getYesterdayDate();

          router.push({
            path: '/workbench/areaalarm',
            query: {
              areaName: areaName,
              warnTime: yesterday
            }
          });
        });

        map.addOverlay(polygon);
      });
    }
  } catch (error) {
    console.error('获取区域数据时发生错误', error);
    ElMessage.error('获取区域数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
});

onUnmounted(() => {
  if (map) {
    map.clearOverlays();
    map = null;
  }
});
</script>

<style scoped>
.map-wrapper {
  width: 100%;
  height: calc(100vh - 84px);
  position: relative;
}

/* 顶部左侧悬浮栏样式 */
.map-header-left {
  position: absolute;
  top: 1%;
  left: 1%;
  z-index: 1000;
  display: flex;
  align-items: center;
  gap: 15px;
}

/* 下拉复选框的布局 */
.dropdown-checkbox {
  padding: 12px;
}
.el-checkbox {
  display: block;
  margin: 6px 0;
}

/* 顶部右侧悬浮栏样式 */
.map-header-right {
  position: absolute;
  top: 1%;
  right: 4%;
  z-index: 1000;
  display: flex;
  align-items: center;
  gap: 15px;
}

.map-container {
  width: 100%;
  height: 100%;
  font-family: "微软雅黑";
}
</style>